package com.revenant.driver.ui.activity;

import java.io.File;
import java.util.ArrayList;
import java.util.ResourceBundle.Control;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.widget.AppCompatEditText;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.apkfuns.logutils.LogUtils;
import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.entity.LocalMedia;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.nanchen.compresshelper.CompressHelper;
import com.revenant.driver.App;
import com.revenant.driver.R;
import com.revenant.driver.adapter.AddNewDriverInfoAdaper;
import com.revenant.driver.base.BaseActivity;
import com.revenant.driver.bean.BaseBean.BaseErrorBean;
import com.revenant.driver.bean.Driver.CarHeadNumSelectBean;
import com.revenant.driver.bean.InviteCode;
import com.revenant.driver.bean.NewDriverAddInfo;
import com.revenant.driver.bean.ShipperBean.FileUploadBean;
import com.revenant.driver.bean.ZIGeZhengBean;
import com.revenant.driver.utils.GsonUtil;
import com.revenant.driver.utils.SPUtils;
import com.revenant.driver.utils.Utils;

import java.util.Arrays;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static android.view.KeyEvent.KEYCODE_BACK;
import static com.revenant.driver.utils.Constants.CallNumber;
import static com.revenant.driver.utils.Constants.CheckcreditQuery;
import static com.revenant.driver.utils.Constants.Improve_Car_Head_Num_Beans;
import static com.revenant.driver.utils.Constants.NewImproveDriverID;
import static com.revenant.driver.utils.Constants.UpdateInvite;
import static com.revenant.driver.utils.Constants.UploadFile;
import static com.revenant.driver.utils.Constants.popMessage;

public class NewImproveDriverInfoaActivity extends BaseActivity {


    @BindView(R.id.new_left)
    ImageView newLeft;
    @BindView(R.id.new_center)
    TextView newCenter;
    @BindView(R.id.new_right)
    ImageView newRight;
    @BindView(R.id.new_show_title)
    LinearLayout newShowTitle;
    @BindView(R.id.new_recyclerview)
    RecyclerView newRecyclerview;
    @BindView(R.id.new_edit)
    AppCompatEditText newEdit;
    @BindView(R.id.new_btn_format)
    Button newBtnFormat;
    private List<String> listName = Arrays.asList(
            "身份证正面",
            "身份证反面",
            "驾驶证正本",
            "驾驶证副本",
            "从业资格证");
    private List<Integer> listImages = Arrays.asList(
            R.mipmap.idforeground,
            R.mipmap.idback,
            R.mipmap.jaishizhengzhengmian,
            R.mipmap.jiashizhengfuye,
            R.mipmap.congyezigezhneg);
    private Context context;
    private List<NewDriverAddInfo> listusers = new ArrayList<>();
    private int selectindex = -1;
    private int selecttype = -1;
    private List<LocalMedia> selectList = new ArrayList<>();
    private AddNewDriverInfoAdaper adaper;
    private int isImages = -1;

    @Override
    public int getContentViewResId() {
        context = this;
        return R.layout.activity_new_improve_driver_infoa;
    }

    @Override
    public void initView() {
        adaper = new AddNewDriverInfoAdaper();
        newRecyclerview.setLayoutManager(new GridLayoutManager(context, 2));
        newRecyclerview.setAdapter(adaper);

        getRenZheng(SPUtils.getAccounId(App.getApplication()));

    }

    @Override
    protected boolean isshowtitlebar() {
        return false;
    }

    @Override
    public void initData() {
        for (int i = 0; i < listName.size(); i++) {
            NewDriverAddInfo user = new NewDriverAddInfo();
            user.setImage(listImages.get(i));
            user.setTitle(listName.get(i));
            user.setImageUrl("");
            listusers.add(user);
        }
        adaper.addData(listusers);

        adaper.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {

                selectindex = position;
                showBottomSheetDialog(NewImproveDriverInfoaActivity.this);
            }
        });

        newCenter.setText("完善司机信息");
        newBtnFormat.setText("提交审核");
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @OnClick({R.id.new_left, R.id.new_right, R.id.new_btn_format})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.new_left:
                selectPopMessage(context, popMessage.get(3));
                break;
            case R.id.new_right:
                selectPhone(NewImproveDriverInfoaActivity.this);
//                Utils.callPhone(NewImproveDriverInfoaActivity.this, CallNumber);
                break;
            case R.id.new_btn_format:
                isImages = -1;
                for (int i = 0; i < listImages.size(); i++) {
                    if (adaper.getData().get(i).getImageUrl().isEmpty()) {
                        showToast("请输入" + listName.get(i));
                        isImages = 0;
                        break;
                    }
                }

                if (isImages != 0 && newEdit.getText().toString().trim().isEmpty()) {
                    showToast("请输入从业资格证号");
                } else if (isImages != 0 && !newEdit.getText().toString().trim().isEmpty()) {
                    // TODO: 2020/6/3
                    String photoa = adaper.getData().get(0).getImageUrl();/*身份证正面*/
                    String photob = adaper.getData().get(1).getImageUrl();/*身份证反面*/
                    String photoc = adaper.getData().get(2).getImageUrl();/*驾驶证正面*/
                    String photod = adaper.getData().get(3).getImageUrl();/*驾驶证反面*/
                    String photoe = adaper.getData().get(4).getImageUrl();/*从业资格证*/
                    updateInvite(photoc, photoe, newEdit.getText().toString(), photoa, photod, photob);
                }
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    selectList = PictureSelector.obtainMultipleResult(data);
                    for (LocalMedia media : selectList) {
                        if (!selectList.isEmpty()) {
                            showDig();
//                            uploadAvatar(media.getPath());
                            String url = media.getPath().startsWith("content://") ? media.getAndroidQToPath() : media.getPath();
                            uploadAvatar(url, selectindex);
                        }
                    }
                    break;
            }
        }
    }


    private void uploadAvatar(final String path, int select) {
        File file = new File(path);
        File newfile = CompressHelper.getDefault(context).compressToFile(file);

        OkGo.<String>post(UploadFile)
                .tag(this)
                .isMultipart(true)

                .params("file", newfile)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        dismissDig();
                        if (response.code() == 200) {
                            FileUploadBean fileUploadBean = GsonUtil.parseJsonWithGson(response.body(), FileUploadBean.class);
                            if (fileUploadBean.getCode().equals("0")) {
                                if (fileUploadBean.getData().getUrl()!=null){
                                    if (!fileUploadBean.getData().getUrl().isEmpty()){
                                        adaper.getData().get(select).setImageUrl(fileUploadBean.getData().getUrl());
                                        adaper.getData().get(select).setSelecttype(0);
                                        adaper.notifyItemChanged(select);
                                    }
                                }


                            } else {
                                showToast(fileUploadBean.getMsg());
                            }
                        } else {
                            showToast(response.message());
                        }

                    }

                    @Override
                    public void onError(Response<String> response) {
                        dismissDig();
                        super.onError(response);
                        showToast(response.message());
                    }
                });
    }

    private void updateInvite(
            String driverUrl,
            String qualificationUrl,
            String qualificationCode,
            String frontUrl,
            String drivingBackLicense,
            String backUrl

    ) {
        OkGo.<String>post(NewImproveDriverID)
                .params("driverUrl", driverUrl)
                .params("qualificationUrl", qualificationUrl)
                .params("accountId", SPUtils.getAccounId(context))
                .params("qualificationCode", qualificationCode)
                .params("frontUrl", frontUrl)
                .params("backUrl", backUrl)
                .params("drivingBackLicense", drivingBackLicense)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        if (response.code() == 200) {
                            BaseErrorBean personal = GsonUtil.parseJsonWithGson(response.body(), BaseErrorBean.class);
                            if (Integer.valueOf(personal.getCode()) == 0) {
                                showLongToast(personal.getMsg());
                                finish();
                            } else {
                                showLongToast(personal.getMsg());
                            }

                        }

                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        showToast(response.message());
                    }
                });
    }




    private void getRenZheng(int driverid) {
        OkGo.<String>get(CheckcreditQuery)
                .params("id", driverid)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        if (response.code() == 200) {

                            ZIGeZhengBean ziGeZhengBean = GsonUtil.parseJsonWithGson(response.body(), ZIGeZhengBean.class);
                            if (ziGeZhengBean.getCode().contains("0")) {

                                String photoa = ziGeZhengBean.getData().getCardFront();/*身份证正面*/
                                String photob = ziGeZhengBean.getData().getCardBack();/*身份证反面*/
                                String photoc = ziGeZhengBean.getData().getValidPh();/*驾驶证正面*/
                                String photod = ziGeZhengBean.getData().getDrivingBackLicense();/*驾驶证反面*/
                                String photof = ziGeZhengBean.getData().getQualificationPhoto();/*从业资格证照片*/

                                String photoe = ziGeZhengBean.getData().getQualificationCertificate();/*从业资格证*/


                                if (photoa != null && !photoa.isEmpty()) {
                                    showadapter(0, photoa);
                                }

                                if (photob != null && !photob.isEmpty()) {
                                    showadapter(1, photob);
                                }

                                if (photoc != null && !photoc.isEmpty()) {
                                    showadapter(2, photoc);
                                }

                                if (photod != null && !photod.isEmpty()) {
                                    showadapter(3, photod);
                                }

                                if (photof != null && !photof.isEmpty()) {
                                    showadapter(4, photof);
                                }

                                newEdit.setText(photoe);
                            }

                        }

                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        showToast(response.message());
                    }
                });
    }

    private void showadapter(int select, String url) {
        adaper.getData().get(select).setImageUrl(url);
        adaper.getData().get(select).setSelecttype(0);
        adaper.notifyItemChanged(select);
    }

    private void selectPopMessage(Context context, String message) {
        AlertDialog alertDialog;
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        View view = getLayoutInflater().inflate(R.layout.popselectmessage, null);
        TextView text = view.findViewById(R.id.popselectmessage);
        text.setText(message);

        TextView cancel = view.findViewById(R.id.cancel);
        TextView ok = view.findViewById(R.id.confirm);

        builder.setView(view);

        alertDialog = builder.show();

        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alertDialog.dismiss();

            }
        });

        ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alertDialog.dismiss();
                finish();

            }
        });
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KEYCODE_BACK) {
            selectPopMessage(context, popMessage.get(3));
            return  false;
        }
        return super.onKeyDown(keyCode, event);
    }
}
